package com.vivo.tasks;

import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.vivo.Utils.DingConfUtil;
import com.vivo.Utils.SendDingDingMsgUtil;
import com.vivo.dingtalk.entity.DingUserInfo;
import com.vivo.dingtalk.entity.OaKqStatics;
import com.vivo.dingtalk.service.DingUserInfoService;
import com.vivo.dingtalk.web.vm.LinkMsgVM;
import com.vivo.employee.service.ViEmployeeService;
import com.vivo.system.entity.VivoDingConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 考勤推送通知
 */
@Component
public class TaskKqNotify {

    @Autowired
    private ViEmployeeService viEmployeeService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private DingUserInfoService dingUserInfoService;

    @Autowired
    private DingConfUtil dingConfUtil;

    public void SyncData() {
//        南京
        kaoqinNotifyByCompId("09eb5a01f7cc424c87fca577acd6dd3e");


        // 通知所有的在南京区域任职为督导的管培生进行推送
        kaoqinNotifyNjGps();

//        simulation();
    }

    /**
     * 通知总经理进行考勤信息汇总通知
     */
    public void SendToZjl() {
        notifyTo(true);
        System.out.println("总经理通知结束");
    }


    /**
     * 通知业务经理进行考勤信息汇总通知
     */
    public void SendToYwjl() {

        notifyTo(false);

        System.out.println("业务经理通知结束");
    }


    /**
     *
     * @param isZjl
     */
    private void notifyTo(boolean isZjl) {
        do {
            // 获取南京所有的考勤统计信息
            List<OaKqStatics> kqStaticsList = dingUserInfoService.getKqStaticsList(isZjl);
            if (kqStaticsList.size() == 0) {
                return;
            }
            String curSpId = kqStaticsList.get(0).getSpId();
            String curSpPhone = kqStaticsList.get(0).getSpTelephone();
            String title = "督导考勤信息汇总";
            String content = "考勤信息统计\n";
            for (OaKqStatics kqStatics : kqStaticsList) {
                // 发送上一天数据信息
                if (!curSpId.equals(kqStatics.getSpId())) {
                    notifyMsgSend(curSpPhone, title, content);

                    curSpId = kqStatics.getSpId();
                    curSpPhone = kqStatics.getSpTelephone();
                    content = "考勤信息统计";
                }

                content += "\n" + kqStatics.getName() + ":\t上报考勤" + kqStatics.getKqDays() + "天,\t未上报" + kqStatics.getUnKqDays() +  "天";
            }

            notifyMsgSend(curSpPhone, title, content);
        } while (false);
    }


    /**
     * 推送考勤打卡信息
     * 推送区域包括：南京城区，南京江北，南京江南
     * 包括兼职信息
     */
    private void kaoqinNotifyByCompId(String compId) {
        List<DingUserInfo> userInfoList = dingUserInfoService.getListByDingCompId(compId);
        VivoDingConf dingConf = dingConfUtil.getDingConf(compId);

        int subSize = 5;
        int subCount = userInfoList.size();
        int subPageTotal = (subCount / subSize) + ((subCount % subSize > 0) ? 1 : 0);
        // 根据页码取数据
        for (int i = 0, len = subPageTotal - 1; i <= len; i++) {
            // 分页计算
            int fromIndex = i * subSize;
            int toIndex = ((i == len) ? subCount : ((i + 1) * subSize));
            List<DingUserInfo> tempUserList = userInfoList.subList(fromIndex, toIndex);

            notifyMsg(tempUserList, dingConf);
        }

        System.out.println("督导考勤信息推送完毕");
    }


    /**
     * 通知南京管培生信息
     */
    private void kaoqinNotifyNjGps() {
        List<DingUserInfo> userInfoList = dingUserInfoService.getKqListByCompName("南京");

        for (DingUserInfo dingUserInfo: userInfoList) {
            VivoDingConf dingConf = dingConfUtil.getDingConf(dingUserInfo.getDingCompId());
            List<DingUserInfo> userInfoList2 = new ArrayList<>();
            userInfoList2.add(dingUserInfo);
            notifyMsg(userInfoList2, dingConf);
        }

        System.out.println("南京管培生兼职督导考勤信息推送完毕");
    }



    /**
     * 模拟测试
     */
    private void simulation() {
        DingUserInfo dingUserInfo = new DingUserInfo();
        dingUserInfo.setDingUserId("014730233521499069");
        List<DingUserInfo> userInfoList = new ArrayList<>();
        userInfoList.add(dingUserInfo);

        VivoDingConf dingConf = new VivoDingConf();
        Office comp = new Office();
        comp.setId("1");
        dingConf.setComp(comp);
        dingConf.setAccessToken("4e5fd59e59893dc09cb26e79497fdbdf");
        dingConf.setAgentId("175472368");

        notifyMsg(userInfoList, dingConf);
    }

    /**
     * 发送数据信息
     * @param loginName
     * @param title
     * @param bodyContent
     */
    private void notifyMsgSend(String loginName, String title, String bodyContent) {
        bodyContent += "\n\n点击进入查看详情";
        do {
            DingUserInfo dingUserInfo = dingUserInfoService.getByMobile(loginName);
            if (dingUserInfo == null) {
                System.out.println("找不到对应的用户钉钉登陆信息！请提醒其进行钉钉登陆操作！");
                continue;
            }

            LinkMsgVM linkMsg = new LinkMsgVM();
            linkMsg.setContent(title);
            linkMsg.setContent(title);
            linkMsg.setBodyContent(bodyContent);
            linkMsg.setPhone(loginName);
            linkMsg.setTitle(title);
            linkMsg.setUrl("http://vivo.jsbstx.com/a/kq/statics?comp=" + dingUserInfo.getDingCompId());
            linkMsg.setDingUserId(dingUserInfo.getDingUserId());

            VivoDingConf dingConf = dingConfUtil.getDingConf(dingUserInfo.getDingCompId());
            if (dingConf == null) {
                System.out.println("该二级区域还没有进行钉钉绑定设置，提醒管理员进行相关绑定操作！二级区域：");
                continue;
            }
            linkMsg.setAccessToken(dingConf.getAccessToken());
            linkMsg.setAgentId(Long.parseLong(dingConf.getAgentId()));

            try {
                OapiMessageCorpconversationAsyncsendV2Response rsp = SendDingDingMsgUtil.sendWorkMsg(linkMsg);
                System.out.println("钉钉链接消息发送成功！");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("消息发送失败" + e.getMessage());
            }
        } while (false);
    }


    private void notifyMsg(List<DingUserInfo> userInfoList, VivoDingConf dingConf) {
        LinkMsgVM linkMsgVM = new LinkMsgVM();
        linkMsgVM.setAgentId(Long.parseLong(dingConf.getAgentId()));
        linkMsgVM.setAccessToken(dingConf.getAccessToken());
        linkMsgVM.setTitle("基层考勤上报提醒");
        linkMsgVM.setContent("基层考勤上报提醒");
        linkMsgVM.setBodyContent("已到考勤管理时间，对基层人员的考勤信息进行上报");
        linkMsgVM.setUrl("http://vivo.jsbstx.com/a/kq/apply?comp=" + dingConf.getComp().getId());

        List<String> dingUserIdList = new ArrayList<>();
        for (DingUserInfo dingUserInfo: userInfoList) {
            dingUserIdList.add(dingUserInfo.getDingUserId());
        }

        linkMsgVM.setDingUserId(String.join(",", dingUserIdList));
        try {
            OapiMessageCorpconversationAsyncsendV2Response response = SendDingDingMsgUtil.sendWorkMsg(linkMsgVM);

            // 请求未成功, 需要挨个进行发送
            if (!response.isSuccess() || response.getErrcode() != 0L) {
                for (DingUserInfo dingUserInfo: userInfoList) {
                    linkMsgVM.setDingUserId(dingUserInfo.getDingUserId());
                    try {
                        OapiMessageCorpconversationAsyncsendV2Response rsp = SendDingDingMsgUtil.sendWorkMsg(linkMsgVM);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TaskKqNotify taskKqNotify = new TaskKqNotify();
        taskKqNotify.SendToZjl();
    }
}
